package com.wuhao.code.check.completion

import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vfs.findPsiFile
import com.intellij.openapi.vfs.newvfs.impl.VirtualDirectoryImpl
import com.intellij.psi.*
import com.wuhao.code.check.cachedPosterity
import org.jetbrains.kotlin.psi.KtFile

/**
 * @author 吴昊
 * @date 2024/02/01
 * @version 1.0
 * @since v1.0.0
 */
class ClassNameReference(
    private val element: PsiElement,
    textRange: TextRange
) : PsiReferenceBase<PsiElement>(
    element, textRange
), PsiPolyVariantReference {

  override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> {
    return arrayOf()
  }

  override fun getRangeInElement(): TextRange {
    return super.getRangeInElement()
  }

  override fun resolve(): PsiElement? {
    val directory = PsiManager.getInstance(element.project).findDirectory(element.project.baseDir)?.virtualFile
    if (directory !is VirtualDirectoryImpl) {
      return null
    }
    val files = directory.cachedPosterity.filter { it.name.endsWith(".java") || it.name.endsWith(".kt") }
    for (file in files) {
      val psiFile = file.findPsiFile(element.project)
      if (psiFile is PsiJavaFile && psiFile.classes.any { it.name == element.text }) {
        return psiFile.classes.find { it.name == element.text }
      } else if (psiFile is KtFile && psiFile.classes.any { it.name == element.text }) {
        return psiFile.classes.find { it.name == element.text }
      }
    }
    return null
  }

}
